import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import CustomCard from '../custom/CustomCard';
import CustomButton from '../custom/CustomButton';
import CustomSelect from '../custom/CustomSelect';
import CustomTag from '../custom/CustomTag';
import CustomAlert from '../custom/CustomAlert';
import CustomSpin from '../custom/CustomSpin';
import CustomProgressBar from '../custom/CustomProgressBar';
import './crawlerStyles.css';

// 模拟爬虫任务数据接口
interface CrawlerJob {
  id: number;
  name: string;
  url: string;
  status: 'pending' | 'running' | 'completed' | 'failed';
  progress: number;
  created_at: string;
  completed_at?: string;
  result_count: number;
  logs?: string[];
}

// 模拟爬虫配置接口
interface CrawlerConfig {
  id: number;
  name: string;
  urls: string[];
  depth: number;
  delay: number;
  user_agent: string;
  is_active: boolean;
  schedule?: {
    enabled: boolean;
    cron: string;
    next_run?: string;
  };
}

// 扩展的调度配置接口
interface ScheduleConfig {
  enabled: boolean;
  cron: string;
  next_run?: string;
}

const CrawlerManager: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [jobs, setJobs] = useState<CrawlerJob[]>([]);
  const [configs, setConfigs] = useState<CrawlerConfig[]>([]);
  const [loading, setLoading] = useState({ jobs: true, configs: true });
  const [activeTab, setActiveTab] = useState<'jobs' | 'configs'>('jobs');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showLogModal, setShowLogModal] = useState<{ jobId: number | null, logs: string[] }>({ jobId: null, logs: [] });
  const [editingConfig, setEditingConfig] = useState<CrawlerConfig | null>(null);
  const [newJob, setNewJob] = useState({ name: '', url: '' });
  const [newConfig, setNewConfig] = useState({
    name: '',
    urls: [''],
    depth: 1,
    delay: 1,
    user_agent: 'Mozilla/5.0 (compatible; Crawler/1.0)',
    is_active: true,
    schedule: {
      enabled: false,
      cron: '0 0 * * *' // 每天 midnight
    } as ScheduleConfig
  });
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedJobs, setSelectedJobs] = useState<number[]>([]);
  const [selectedConfigs, setSelectedConfigs] = useState<number[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [exportFormat, setExportFormat] = useState<'csv' | 'json'>('csv');

  // 模拟获取爬虫任务数据
  const fetchJobs = async () => {
    try {
      setLoading(prev => ({ ...prev, jobs: true }));
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockJobs: CrawlerJob[] = [
        {
          id: 1,
          name: '新闻网站爬取',
          url: 'https://news.example.com',
          status: 'completed',
          progress: 100,
          created_at: '2023-01-01T10:00:00Z',
          completed_at: '2023-01-01T10:05:00Z',
          result_count: 1250,
          logs: [
            '[2023-01-01 10:00:00] INFO: 开始爬取任务: 新闻网站爬取',
            '[2023-01-01 10:00:01] INFO: 连接到 https://news.example.com',
            '[2023-01-01 10:00:05] INFO: 发现 150 个页面链接',
            '[2023-01-01 10:02:30] WARNING: 页面 https://news.example.com/article/45 响应超时',
            '[2023-01-01 10:05:00] SUCCESS: 爬取完成，共获取 1250 条数据'
          ]
        },
        {
          id: 2,
          name: '电商数据抓取',
          url: 'https://shop.example.com',
          status: 'running',
          progress: 65,
          created_at: '2023-01-01T11:00:00Z',
          result_count: 842,
          logs: [
            '[2023-01-01 11:00:00] INFO: 开始爬取任务: 电商数据抓取',
            '[2023-01-01 11:00:02] INFO: 连接到 https://shop.example.com',
            '[2023-01-01 11:00:10] INFO: 发现 320 个商品页面',
            '[2023-01-01 11:05:20] INFO: 已获取 500 条商品数据',
            '[2023-01-01 11:10:15] INFO: 正在处理商品详情...'
          ]
        },
        {
          id: 3,
          name: '社交媒体分析',
          url: 'https://social.example.com',
          status: 'pending',
          progress: 0,
          created_at: '2023-01-01T12:00:00Z',
          result_count: 0
        }
      ];
      
      setJobs(mockJobs);
    } catch (error) {
      console.error('获取爬虫任务失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, jobs: false }));
    }
  };

  // 模拟获取爬虫配置数据
  const fetchConfigs = async () => {
    try {
      setLoading(prev => ({ ...prev, configs: true }));
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockConfigs: CrawlerConfig[] = [
        {
          id: 1,
          name: '新闻爬虫配置',
          urls: ['https://news.example.com/*'],
          depth: 2,
          delay: 2,
          user_agent: 'Mozilla/5.0 (compatible; NewsCrawler/1.0)',
          is_active: true,
          schedule: {
            enabled: true,
            cron: '0 9 * * *', // 每天 9:00 AM
            next_run: '2023-01-02T09:00:00Z'
          }
        },
        {
          id: 2,
          name: '电商爬虫配置',
          urls: ['https://shop.example.com/*', 'https://market.example.com/*'],
          depth: 3,
          delay: 1,
          user_agent: 'Mozilla/5.0 (compatible; ShopCrawler/1.0)',
          is_active: false,
          schedule: {
            enabled: false,
            cron: '0 0 * * *'
          }
        }
      ];
      
      setConfigs(mockConfigs);
    } catch (error) {
      console.error('获取爬虫配置失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, configs: false }));
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchJobs();
    fetchConfigs();
  }, []);

  // 获取状态标签颜色
  const getStatusColor = (status: CrawlerJob['status']) => {
    switch (status) {
      case 'completed': return 'success';
      case 'running': return 'processing';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  // 获取状态文本
  const getStatusText = (status: CrawlerJob['status']) => {
    switch (status) {
      case 'completed': return '已完成';
      case 'running': return '运行中';
      case 'failed': return '失败';
      default: return '待处理';
    }
  };

  // 创建新任务
  const handleCreateJob = () => {
    if (!newJob.name || !newJob.url) return;
    
    const job: CrawlerJob = {
      id: Date.now(),
      name: newJob.name,
      url: newJob.url,
      status: 'pending',
      progress: 0,
      created_at: new Date().toISOString(),
      result_count: 0
    };
    
    setJobs(prev => [job, ...prev]);
    setNewJob({ name: '', url: '' });
    setShowCreateModal(false);
  };

  // 创建新配置
  const handleCreateConfig = () => {
    if (!newConfig.name) return;
    
    const config: CrawlerConfig = {
      id: Date.now(),
      name: newConfig.name,
      urls: newConfig.urls.filter(url => url.trim() !== ''),
      depth: newConfig.depth,
      delay: newConfig.delay,
      user_agent: newConfig.user_agent,
      is_active: newConfig.is_active,
      schedule: newConfig.schedule
    };
    
    setConfigs(prev => [config, ...prev]);
    setNewConfig({
      name: '',
      urls: [''],
      depth: 1,
      delay: 1,
      user_agent: 'Mozilla/5.0 (compatible; Crawler/1.0)',
      is_active: true,
      schedule: {
        enabled: false,
        cron: '0 0 * * *'
      } as ScheduleConfig
    });
    setShowCreateModal(false);
  };

  // 编辑配置
  const handleEditConfig = (config: CrawlerConfig) => {
    setEditingConfig(config);
    setNewConfig({
      name: config.name,
      urls: [...config.urls],
      depth: config.depth,
      delay: config.delay,
      user_agent: config.user_agent,
      is_active: config.is_active,
      schedule: config.schedule || {
        enabled: false,
        cron: '0 0 * * *'
      } as ScheduleConfig
    });
    setShowCreateModal(true);
  };

  // 保存编辑的配置
  const handleSaveConfig = () => {
    if (!newConfig.name || !editingConfig) return;
    
    const updatedConfigs = configs.map(config => 
      config.id === editingConfig.id ? {
        ...config,
        name: newConfig.name,
        urls: newConfig.urls.filter(url => url.trim() !== ''),
        depth: newConfig.depth,
        delay: newConfig.delay,
        user_agent: newConfig.user_agent,
        is_active: newConfig.is_active,
        schedule: newConfig.schedule
      } : config
    );
    
    setConfigs(updatedConfigs);
    setEditingConfig(null);
    setNewConfig({
      name: '',
      urls: [''],
      depth: 1,
      delay: 1,
      user_agent: 'Mozilla/5.0 (compatible; Crawler/1.0)',
      is_active: true,
      schedule: {
        enabled: false,
        cron: '0 0 * * *'
      } as ScheduleConfig
    });
    setShowCreateModal(false);
  };

  // 添加URL输入框
  const addUrlField = () => {
    setNewConfig(prev => ({
      ...prev,
      urls: [...prev.urls, '']
    }));
  };

  // 更新URL输入框
  const updateUrlField = (index: number, value: string) => {
    setNewConfig(prev => {
      const urls = [...prev.urls];
      urls[index] = value;
      return { ...prev, urls };
    });
  };

  // 删除URL输入框
  const removeUrlField = (index: number) => {
    if (newConfig.urls.length <= 1) return;
    setNewConfig(prev => {
      const urls = [...prev.urls];
      urls.splice(index, 1);
      return { ...prev, urls };
    });
  };

  // 启动任务
  const startJob = (id: number) => {
    setJobs(prev => prev.map(job => 
      job.id === id ? { ...job, status: 'running', progress: 10 } : job
    ));
  };

  // 停止任务
  const stopJob = (id: number) => {
    setJobs(prev => prev.map(job => 
      job.id === id ? { ...job, status: 'pending', progress: 0 } : job
    ));
  };

  // 删除任务
  const deleteJob = (id: number) => {
    setJobs(prev => prev.filter(job => job.id !== id));
    setSelectedJobs(prev => prev.filter(jobId => jobId !== id));
  };

  // 删除配置
  const deleteConfig = (id: number) => {
    setConfigs(prev => prev.filter(config => config.id !== id));
    setSelectedConfigs(prev => prev.filter(configId => configId !== id));
  };

  // 批量删除任务
  const batchDeleteJobs = () => {
    setJobs(prev => prev.filter(job => !selectedJobs.includes(job.id)));
    setSelectedJobs([]);
  };

  // 批量删除配置
  const batchDeleteConfigs = () => {
    setConfigs(prev => prev.filter(config => !selectedConfigs.includes(config.id)));
    setSelectedConfigs([]);
  };

  // 查看任务日志
  const viewJobLogs = (jobId: number) => {
    const job = jobs.find(j => j.id === jobId);
    if (job && job.logs) {
      setShowLogModal({ jobId, logs: job.logs });
    }
  };

  // 导出数据
  const exportData = () => {
    // 模拟导出功能
    alert(`数据已导出为 ${exportFormat} 格式`);
  };

  // 选择/取消选择任务
  const toggleJobSelection = (id: number) => {
    setSelectedJobs(prev => 
      prev.includes(id) 
        ? prev.filter(jobId => jobId !== id) 
        : [...prev, id]
    );
  };

  // 选择/取消选择配置
  const toggleConfigSelection = (id: number) => {
    setSelectedConfigs(prev => 
      prev.includes(id) 
        ? prev.filter(configId => configId !== id) 
        : [...prev, id]
    );
  };

  // 全选/取消全选任务
  const toggleAllJobs = () => {
    if (selectedJobs.length === getCurrentPageJobs().length) {
      setSelectedJobs([]);
    } else {
      setSelectedJobs(getCurrentPageJobs().map(job => job.id));
    }
  };

  // 全选/取消全选配置
  const toggleAllConfigs = () => {
    if (selectedConfigs.length === getCurrentPageConfigs().length) {
      setSelectedConfigs([]);
    } else {
      setSelectedConfigs(getCurrentPageConfigs().map(config => config.id));
    }
  };

  // 获取当前页的任务
  const getCurrentPageJobs = () => {
    const filtered = jobs.filter(job => 
      job.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      job.url.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filtered.slice(startIndex, startIndex + itemsPerPage);
  };

  // 获取当前页的配置
  const getCurrentPageConfigs = () => {
    const filtered = configs.filter(config => 
      config.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      config.urls.some(url => url.toLowerCase().includes(searchTerm.toLowerCase()))
    );
    
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filtered.slice(startIndex, startIndex + itemsPerPage);
  };

  // 计算总页数
  const getTotalPages = (items: any[]) => {
    return Math.ceil(items.length / itemsPerPage);
  };

  // 过滤任务
  const filteredJobs = jobs.filter(job => 
    job.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    job.url.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 过滤配置
  const filteredConfigs = configs.filter(config => 
    config.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    config.urls.some(url => url.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  // 计算统计信息
  const jobStats = {
    total: jobs.length,
    pending: jobs.filter(job => job.status === 'pending').length,
    running: jobs.filter(job => job.status === 'running').length,
    completed: jobs.filter(job => job.status === 'completed').length,
    failed: jobs.filter(job => job.status === 'failed').length,
    results: jobs.reduce((sum, job) => sum + job.result_count, 0)
  };

  const configStats = {
    total: configs.length,
    active: configs.filter(config => config.is_active).length,
    inactive: configs.filter(config => !config.is_active).length
  };

  return (
    <motion.div 
      className="crawler-manager"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      style={{ 
        backgroundColor: theme.contentBackground,
        color: theme.textPrimary,
      }}
    >
      <div className="crawler-header">
        <motion.h1 
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 0.5 }}
          className="crawler-title"
          style={{ 
            background: mode === 'dark' 
              ? 'linear-gradient(90deg, #61dca3, #1890ff)' 
              : 'linear-gradient(90deg, #1890ff, #61dca3)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text'
          }}
        >
          🕷️ 智能爬虫系统
        </motion.h1>
        <motion.p 
          initial={{ y: -10, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="crawler-subtitle"
          style={{ 
            color: theme.textSecondary,
          }}
        >
          支持静态/动态网页爬取，分布式任务调度
        </motion.p>
      </div>

      {/* 统计信息卡片 */}
      <div className="crawler-stats-grid">
        <CustomCard className="crawler-stat-card">
          <div className="crawler-stat-content">
            <div className="crawler-stat-icon" style={{ 
              backgroundColor: mode === 'dark' ? 'rgba(24, 144, 255, 0.2)' : 'rgba(24, 144, 255, 0.1)',
            }}>
              <span>🕷️</span>
            </div>
            <div>
              <p className="crawler-stat-text" style={{ color: theme.textSecondary }}>任务总数</p>
              <p className="crawler-stat-value" style={{ color: theme.textPrimary }}>{jobStats.total}</p>
            </div>
          </div>
        </CustomCard>
        
        <CustomCard className="crawler-stat-card">
          <div className="crawler-stat-content">
            <div className="crawler-stat-icon" style={{ 
              backgroundColor: mode === 'dark' ? 'rgba(97, 220, 163, 0.2)' : 'rgba(97, 220, 163, 0.1)',
            }}>
              <span>⚙️</span>
            </div>
            <div>
              <p className="crawler-stat-text" style={{ color: theme.textSecondary }}>配置总数</p>
              <p className="crawler-stat-value" style={{ color: theme.textPrimary }}>{configStats.total}</p>
            </div>
          </div>
        </CustomCard>
        
        <CustomCard className="crawler-stat-card">
          <div className="crawler-stat-content">
            <div className="crawler-stat-icon" style={{ 
              backgroundColor: mode === 'dark' ? 'rgba(255, 77, 79, 0.2)' : 'rgba(255, 77, 79, 0.1)',
            }}>
              <span>📊</span>
            </div>
            <div>
              <p className="crawler-stat-text" style={{ color: theme.textSecondary }}>总结果数</p>
              <p className="crawler-stat-value" style={{ color: theme.textPrimary }}>{jobStats.results}</p>
            </div>
          </div>
        </CustomCard>
      </div>

      <div className="crawler-main-content">
        <CustomCard className="crawler-card">
          <div 
            className="crawler-tab-header"
            style={{ 
              borderBottom: `1px solid ${theme.borderColor}`,
            }}
          >
            <div className="crawler-tab-buttons">
              <CustomButton
                type={activeTab === 'jobs' ? 'primary' : 'default'}
                onClick={() => {
                  setActiveTab('jobs');
                  setCurrentPage(1);
                }}
              >
                爬虫任务
              </CustomButton>
              <CustomButton
                type={activeTab === 'configs' ? 'primary' : 'default'}
                onClick={() => {
                  setActiveTab('configs');
                  setCurrentPage(1);
                }}
              >
                爬虫配置
              </CustomButton>
            </div>
            <div className="crawler-search-container">
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => {
                  setSearchTerm(e.target.value);
                  setCurrentPage(1);
                }}
                placeholder={`搜索${activeTab === 'jobs' ? '任务' : '配置'}...`}
                className="crawler-search-input"
                style={{
                  border: `1px solid ${theme.borderColor}`,
                  backgroundColor: mode === 'dark' 
                    ? 'rgba(255, 255, 255, 0.05)' 
                    : 'rgba(0, 0, 0, 0.03)',
                  color: theme.textPrimary,
                }}
              />
              <div className="crawler-action-buttons">
                {activeTab === 'jobs' && (
                  <CustomButton
                    type="default"
                    onClick={exportData}
                    disabled={jobs.length === 0}
                  >
                    导出数据
                  </CustomButton>
                )}
                <CustomButton
                  type="primary"
                  onClick={() => {
                    setEditingConfig(null);
                    setShowCreateModal(true);
                  }}
                >
                  {activeTab === 'jobs' ? '新建任务' : '新建配置'}
                </CustomButton>
              </div>
            </div>
          </div>

          {activeTab === 'jobs' ? (
            <div>
              {selectedJobs.length > 0 && (
                <div className="crawler-batch-actions" style={{ 
                  borderBottom: `1px solid ${theme.borderColor}`,
                  color: theme.textSecondary,
                }}>
                  <div>
                    已选择 {selectedJobs.length} 项
                  </div>
                  <CustomButton 
                    type="danger" 
                    size="small"
                    onClick={batchDeleteJobs}
                  >
                    批量删除
                  </CustomButton>
                </div>
              )}
              
              {loading.jobs ? (
                <div className="crawler-empty-state">
                  <CustomSpin />
                  <p style={{ color: theme.textSecondary, marginTop: '16px' }}>正在加载爬虫任务...</p>
                </div>
              ) : getCurrentPageJobs().length === 0 ? (
                <div className="crawler-empty-state" style={{ color: theme.textSecondary }}>
                  <span className="crawler-empty-icon">🕷️</span>
                  <p>{searchTerm ? '未找到匹配的任务' : '暂无爬虫任务'}</p>
                  <CustomButton 
                    type="primary" 
                    style={{ marginTop: '16px' }}
                    onClick={() => {
                      setEditingConfig(null);
                      setShowCreateModal(true);
                    }}
                  >
                    {searchTerm ? '清除搜索' : '创建第一个任务'}
                  </CustomButton>
                  {searchTerm && (
                    <CustomButton 
                      type="default" 
                      style={{ marginTop: '16px', marginLeft: '12px' }}
                      onClick={() => setSearchTerm('')}
                    >
                      清除搜索
                    </CustomButton>
                  )}
                </div>
              ) : (
                <div>
                  <div className="crawler-table-header" style={{ 
                    backgroundColor: mode === 'dark' 
                      ? 'rgba(255, 255, 255, 0.05)' 
                      : 'rgba(0, 0, 0, 0.03)',
                    border: `1px solid ${theme.borderColor}`,
                  }}>
                    <div className="crawler-table-cell-checkbox">
                      <input
                        type="checkbox"
                        checked={selectedJobs.length === getCurrentPageJobs().length && getCurrentPageJobs().length > 0}
                        onChange={toggleAllJobs}
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                    <div style={{ flex: 1, fontWeight: 500, color: theme.textPrimary }}>任务名称</div>
                    <div className="crawler-table-cell-status" style={{ fontWeight: 500, color: theme.textPrimary }}>状态</div>
                    <div className="crawler-table-cell-progress" style={{ fontWeight: 500, color: theme.textPrimary }}>进度</div>
                    <div className="crawler-table-cell-count" style={{ fontWeight: 500, color: theme.textPrimary }}>结果数</div>
                    <div className="crawler-table-cell-actions" style={{ fontWeight: 500, color: theme.textPrimary }}>操作</div>
                  </div>
                  
                  {getCurrentPageJobs().map(job => (
                    <motion.div
                      key={job.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.3 }}
                      className="crawler-table-row"
                      style={{
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        border: `1px solid ${theme.cardBorder}`,
                        boxShadow: theme.cardShadow,
                      }}
                    >
                      <div className="crawler-table-cell-checkbox">
                        <input
                          type="checkbox"
                          checked={selectedJobs.includes(job.id)}
                          onChange={() => toggleJobSelection(job.id)}
                          style={{ cursor: 'pointer' }}
                        />
                      </div>
                      <div className="crawler-table-cell-name">
                        <h3 className="crawler-job-name" style={{ 
                          color: theme.textPrimary,
                        }}>
                          {job.name}
                        </h3>
                        <p className="crawler-job-url" style={{ 
                          color: theme.textSecondary,
                        }}>
                          {job.url}
                        </p>
                      </div>
                      <div className="crawler-table-cell-status">
                        <CustomTag color={getStatusColor(job.status)}>
                          {getStatusText(job.status)}
                        </CustomTag>
                      </div>
                      <div className="crawler-table-cell-progress">
                        {job.status === 'running' ? (
                          <CustomProgressBar percent={job.progress} showInfo />
                        ) : (
                          <span style={{ color: theme.textPrimary }}>{job.progress}%</span>
                        )}
                      </div>
                      <div className="crawler-table-cell-count">
                        <span style={{ color: theme.textPrimary }}>{job.result_count}</span>
                      </div>
                      <div className="crawler-table-cell-actions">
                        {job.status === 'pending' && (
                          <CustomButton 
                            type="primary"
                            size="small"
                            onClick={() => startJob(job.id)}
                          >
                            启动
                          </CustomButton>
                        )}
                        {job.status === 'running' && (
                          <CustomButton 
                            type="secondary"
                            size="small"
                            onClick={() => stopJob(job.id)}
                          >
                            停止
                          </CustomButton>
                        )}
                        <CustomButton 
                          type="default"
                          size="small"
                          onClick={() => viewJobLogs(job.id)}
                        >
                          日志
                        </CustomButton>
                        <CustomButton 
                          type="default"
                          size="small"
                          onClick={() => deleteJob(job.id)}
                        >
                          删除
                        </CustomButton>
                      </div>
                    </motion.div>
                  ))}
                  
                  {/* 分页 */}
                  {getTotalPages(filteredJobs) > 1 && (
                    <div style={{ 
                      display: 'flex', 
                      justifyContent: 'center', 
                      marginTop: '24px',
                      gap: '8px'
                    }}>
                      {[...Array(getTotalPages(filteredJobs))].map((_, index) => (
                        <CustomButton
                          key={index}
                          type={currentPage === index + 1 ? 'primary' : 'default'}
                          size="small"
                          onClick={() => setCurrentPage(index + 1)}
                        >
                          {index + 1}
                        </CustomButton>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          ) : (
            <div>
              {selectedConfigs.length > 0 && (
                <div className="crawler-batch-actions" style={{ 
                  borderBottom: `1px solid ${theme.borderColor}`,
                  color: theme.textSecondary,
                }}>
                  <div>
                    已选择 {selectedConfigs.length} 项
                  </div>
                  <CustomButton 
                    type="danger" 
                    size="small"
                    onClick={batchDeleteConfigs}
                  >
                    批量删除
                  </CustomButton>
                </div>
              )}
              
              {loading.configs ? (
                <div className="crawler-empty-state">
                  <CustomSpin />
                  <p style={{ color: theme.textSecondary, marginTop: '16px' }}>正在加载爬虫配置...</p>
                </div>
              ) : getCurrentPageConfigs().length === 0 ? (
                <div className="crawler-empty-state" style={{ color: theme.textSecondary }}>
                  <span className="crawler-empty-icon">⚙️</span>
                  <p>{searchTerm ? '未找到匹配的配置' : '暂无爬虫配置'}</p>
                  <CustomButton 
                    type="primary" 
                    style={{ marginTop: '16px' }}
                    onClick={() => {
                      setEditingConfig(null);
                      setShowCreateModal(true);
                    }}
                  >
                    {searchTerm ? '清除搜索' : '创建第一个配置'}
                  </CustomButton>
                  {searchTerm && (
                    <CustomButton 
                      type="default" 
                      style={{ marginTop: '16px', marginLeft: '12px' }}
                      onClick={() => setSearchTerm('')}
                    >
                      清除搜索
                    </CustomButton>
                  )}
                </div>
              ) : (
                <div>
                  <div className="crawler-table-header" style={{ 
                    backgroundColor: mode === 'dark' 
                      ? 'rgba(255, 255, 255, 0.05)' 
                      : 'rgba(0, 0, 0, 0.03)',
                    border: `1px solid ${theme.borderColor}`,
                  }}>
                    <div className="crawler-table-cell-checkbox">
                      <input
                        type="checkbox"
                        checked={selectedConfigs.length === getCurrentPageConfigs().length && getCurrentPageConfigs().length > 0}
                        onChange={toggleAllConfigs}
                        style={{ cursor: 'pointer' }}
                      />
                    </div>
                    <div style={{ flex: 1, fontWeight: 500, color: theme.textPrimary }}>配置名称</div>
                    <div style={{ width: '150px', fontWeight: 500, color: theme.textPrimary }}>状态</div>
                    <div style={{ width: '100px', fontWeight: 500, color: theme.textPrimary }}>URL数量</div>
                    <div className="crawler-table-cell-actions" style={{ fontWeight: 500, color: theme.textPrimary }}>操作</div>
                  </div>
                  
                  {getCurrentPageConfigs().map(config => (
                    <motion.div
                      key={config.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.3 }}
                      className="crawler-table-row"
                      style={{
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        border: `1px solid ${theme.cardBorder}`,
                        boxShadow: theme.cardShadow,
                      }}
                    >
                      <div className="crawler-table-cell-checkbox">
                        <input
                          type="checkbox"
                          checked={selectedConfigs.includes(config.id)}
                          onChange={() => toggleConfigSelection(config.id)}
                          style={{ cursor: 'pointer' }}
                        />
                      </div>
                      <div className="crawler-table-cell-name">
                        <h3 className="crawler-job-name" style={{ 
                          color: theme.textPrimary,
                        }}>
                          {config.name}
                        </h3>
                        <div className="crawler-table-cell-urls">
                          {config.urls.slice(0, 2).map((url, index) => (
                            <CustomTag 
                              key={index} 
                              color="blue"
                            >
                              {url}
                            </CustomTag>
                          ))}
                          {config.urls.length > 2 && (
                            <CustomTag 
                              color="default"
                            >
                              +{config.urls.length - 2}
                            </CustomTag>
                          )}
                        </div>
                      </div>
                      <div style={{ width: '150px' }}>
                        <CustomTag color={config.is_active ? 'success' : 'default'}>
                          {config.is_active ? '启用' : '禁用'}
                        </CustomTag>
                      </div>
                      <div style={{ width: '100px' }}>
                        <span style={{ color: theme.textPrimary }}>{config.urls.length}</span>
                      </div>
                      <div className="crawler-table-cell-actions">
                        <CustomButton 
                          type="default"
                          size="small"
                          onClick={() => handleEditConfig(config)}
                        >
                          编辑
                        </CustomButton>
                        <CustomButton 
                          type="danger"
                          size="small"
                          onClick={() => deleteConfig(config.id)}
                        >
                          删除
                        </CustomButton>
                      </div>
                    </motion.div>
                  ))}
                  
                  {/* 分页 */}
                  {getTotalPages(filteredConfigs) > 1 && (
                    <div style={{ 
                      display: 'flex', 
                      justifyContent: 'center', 
                      marginTop: '24px',
                      gap: '8px'
                    }}>
                      {[...Array(getTotalPages(filteredConfigs))].map((_, index) => (
                        <CustomButton
                          key={index}
                          type={currentPage === index + 1 ? 'primary' : 'default'}
                          size="small"
                          onClick={() => setCurrentPage(index + 1)}
                        >
                          {index + 1}
                        </CustomButton>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </CustomCard>
      </div>

      {/* 创建/编辑任务/配置模态框 */}
      {showCreateModal && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="crawler-modal-overlay"
        >
          <motion.div
            initial={{ scale: 0.7, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.7, opacity: 0 }}
            className="crawler-modal-content"
            style={{
              backgroundColor: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              boxShadow: theme.cardShadow
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div 
              className="crawler-modal-header"
              style={{ 
                borderBottom: `1px solid ${theme.borderColor}`,
              }}
            >
              <h2 className="crawler-modal-title" style={{ 
                color: theme.textPrimary,
              }}>
                {editingConfig 
                  ? '编辑爬虫配置' 
                  : activeTab === 'jobs' 
                    ? '创建爬虫任务' 
                    : '创建爬虫配置'}
              </h2>
              <button
                className="crawler-modal-close"
                style={{
                  color: theme.textSecondary,
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = theme.glowColor}
                onMouseLeave={(e) => e.currentTarget.style.color = theme.textSecondary}
                onClick={() => {
                  setShowCreateModal(false);
                  setEditingConfig(null);
                }}
              >
                ×
              </button>
            </div>
            
            <div className="crawler-modal-body">
              {activeTab === 'jobs' && !editingConfig ? (
                <div className="crawler-form-group">
                  <div className="crawler-form-field">
                    <label className="crawler-form-label" style={{ 
                      color: theme.textPrimary,
                    }}>
                      任务名称
                    </label>
                    <input
                      type="text"
                      value={newJob.name}
                      onChange={(e) => setNewJob(prev => ({ ...prev, name: e.target.value }))}
                      className="crawler-form-input"
                      style={{
                        border: `1px solid ${theme.borderColor}`,
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        color: theme.textPrimary,
                      }}
                      placeholder="请输入任务名称"
                    />
                  </div>
                  
                  <div className="crawler-form-field">
                    <label className="crawler-form-label" style={{ 
                      color: theme.textPrimary,
                    }}>
                      目标URL
                    </label>
                    <input
                      type="text"
                      value={newJob.url}
                      onChange={(e) => setNewJob(prev => ({ ...prev, url: e.target.value }))}
                      className="crawler-form-input"
                      style={{
                        border: `1px solid ${theme.borderColor}`,
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        color: theme.textPrimary,
                      }}
                      placeholder="请输入要爬取的URL"
                    />
                  </div>
                  
                  <div className="crawler-modal-footer">
                    <CustomButton 
                      type="default"
                      onClick={() => {
                        setShowCreateModal(false);
                        setEditingConfig(null);
                      }}
                    >
                      取消
                    </CustomButton>
                    <CustomButton 
                      type="primary"
                      onClick={handleCreateJob}
                      disabled={!newJob.name || !newJob.url}
                    >
                      创建任务
                    </CustomButton>
                  </div>
                </div>
              ) : (
                <div className="crawler-form-group">
                  <div className="crawler-form-field">
                    <label className="crawler-form-label" style={{ 
                      color: theme.textPrimary,
                    }}>
                      配置名称
                    </label>
                    <input
                      type="text"
                      value={newConfig.name}
                      onChange={(e) => setNewConfig(prev => ({ ...prev, name: e.target.value }))}
                      className="crawler-form-input"
                      style={{
                        border: `1px solid ${theme.borderColor}`,
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        color: theme.textPrimary,
                      }}
                      placeholder="请输入配置名称"
                    />
                  </div>
                  
                  <div className="crawler-form-field">
                    <label className="crawler-form-label" style={{ 
                      color: theme.textPrimary,
                    }}>
                      目标URLs
                    </label>
                    {newConfig.urls.map((url, index) => (
                      <div key={index} className="crawler-url-field">
                        <input
                          type="text"
                          value={url}
                          onChange={(e) => updateUrlField(index, e.target.value)}
                          className="crawler-form-input"
                          style={{
                            border: `1px solid ${theme.borderColor}`,
                            backgroundColor: mode === 'dark' 
                              ? 'rgba(255, 255, 255, 0.05)' 
                              : 'rgba(0, 0, 0, 0.03)',
                            color: theme.textPrimary,
                          }}
                          placeholder="请输入要爬取的URL"
                        />
                        {newConfig.urls.length > 1 && (
                          <CustomButton
                            type="danger"
                            size="small"
                            onClick={() => removeUrlField(index)}
                          >
                            删除
                          </CustomButton>
                        )}
                      </div>
                    ))}
                    <CustomButton
                      type="default"
                      size="small"
                      onClick={addUrlField}
                      style={{ marginTop: '8px' }}
                    >
                      添加URL
                    </CustomButton>
                  </div>
                  
                  <div className="crawler-form-grid">
                    <div className="crawler-form-field">
                      <label className="crawler-form-label" style={{ 
                        color: theme.textPrimary,
                      }}>
                        爬取深度
                      </label>
                      <input
                        type="number"
                        min="1"
                        max="10"
                        value={newConfig.depth}
                        onChange={(e) => setNewConfig(prev => ({ ...prev, depth: parseInt(e.target.value) || 1 }))}
                        className="crawler-form-input"
                        style={{
                          border: `1px solid ${theme.borderColor}`,
                          backgroundColor: mode === 'dark' 
                            ? 'rgba(255, 255, 255, 0.05)' 
                            : 'rgba(0, 0, 0, 0.03)',
                          color: theme.textPrimary,
                        }}
                      />
                    </div>
                    
                    <div className="crawler-form-field">
                      <label className="crawler-form-label" style={{ 
                        color: theme.textPrimary,
                      }}>
                        请求延迟(秒)
                      </label>
                      <input
                        type="number"
                        min="0"
                        max="60"
                        step="0.5"
                        value={newConfig.delay}
                        onChange={(e) => setNewConfig(prev => ({ ...prev, delay: parseFloat(e.target.value) || 1 }))}
                        className="crawler-form-input"
                        style={{
                          border: `1px solid ${theme.borderColor}`,
                          backgroundColor: mode === 'dark' 
                            ? 'rgba(255, 255, 255, 0.05)' 
                            : 'rgba(0, 0, 0, 0.03)',
                          color: theme.textPrimary,
                        }}
                      />
                    </div>
                  </div>
                  
                  <div className="crawler-form-field">
                    <label className="crawler-form-label" style={{ 
                      color: theme.textPrimary,
                    }}>
                      User-Agent
                    </label>
                    <input
                      type="text"
                      value={newConfig.user_agent}
                      onChange={(e) => setNewConfig(prev => ({ ...prev, user_agent: e.target.value }))}
                      className="crawler-form-input"
                      style={{
                        border: `1px solid ${theme.borderColor}`,
                        backgroundColor: mode === 'dark' 
                          ? 'rgba(255, 255, 255, 0.05)' 
                          : 'rgba(0, 0, 0, 0.03)',
                        color: theme.textPrimary,
                      }}
                      placeholder="请输入User-Agent"
                    />
                  </div>
                  
                  <div className="crawler-form-field">
                    <div className="crawler-toggle-container" style={{ 
                      color: theme.textPrimary,
                    }}>
                      <div
                        className="crawler-toggle-switch"
                        style={{
                          backgroundColor: newConfig.is_active 
                            ? (mode === 'dark' ? 'rgba(97, 220, 163, 0.5)' : 'rgba(24, 144, 255, 0.3)') 
                            : (mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'),
                        }}
                        onClick={() => setNewConfig(prev => ({ ...prev, is_active: !prev.is_active }))}
                      >
                        <div 
                          className="crawler-toggle-handle"
                          style={{
                            left: newConfig.is_active ? '22px' : '2px',
                            backgroundColor: mode === 'dark' ? '#fff' : '#000',
                          }}
                        />
                      </div>
                      <span>启用配置</span>
                    </div>
                  </div>
                  
                  {/* 调度配置 */}
                  <div className="crawler-form-field">
                    <div className="crawler-toggle-container" style={{ 
                      color: theme.textPrimary,
                    }}>
                      <div
                        className="crawler-toggle-switch"
                        style={{
                          backgroundColor: newConfig.schedule.enabled 
                            ? (mode === 'dark' ? 'rgba(97, 220, 163, 0.5)' : 'rgba(24, 144, 255, 0.3)') 
                            : (mode === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'),
                        }}
                        onClick={() => setNewConfig(prev => ({
                          ...prev,
                          schedule: { ...prev.schedule, enabled: !prev.schedule.enabled }
                        }))}
                      >
                        <div 
                          className="crawler-toggle-handle"
                          style={{
                            left: newConfig.schedule.enabled ? '22px' : '2px',
                            backgroundColor: mode === 'dark' ? '#fff' : '#000',
                          }}
                        />
                      </div>
                      <span>启用定时调度</span>
                    </div>
                  </div>
                  
                  {newConfig.schedule.enabled && (
                    <div className="crawler-schedule-config">
                      <div className="crawler-form-field">
                        <label className="crawler-form-label" style={{ 
                          color: theme.textPrimary,
                        }}>
                          Cron表达式
                        </label>
                        <input
                          type="text"
                          value={newConfig.schedule.cron}
                          onChange={(e) => setNewConfig(prev => ({
                            ...prev,
                            schedule: { ...prev.schedule, cron: e.target.value }
                          }))}
                          className="crawler-form-input"
                          style={{
                            border: `1px solid ${theme.borderColor}`,
                            backgroundColor: mode === 'dark' 
                              ? 'rgba(255, 255, 255, 0.05)' 
                              : 'rgba(0, 0, 0, 0.03)',
                            color: theme.textPrimary,
                          }}
                          placeholder="例如: 0 0 * * *"
                        />
                      </div>
                      
                      <div className="crawler-form-field">
                        <label className="crawler-form-label" style={{ 
                          color: theme.textPrimary,
                        }}>
                          下次运行时间
                        </label>
                        <input
                          type="text"
                          value={newConfig.schedule.next_run || ''}
                          onChange={(e) => setNewConfig(prev => ({
                            ...prev,
                            schedule: { 
                              ...prev.schedule, 
                              next_run: e.target.value || undefined
                            }
                          }))}
                          className="crawler-form-input"
                          style={{
                            border: `1px solid ${theme.borderColor}`,
                            backgroundColor: mode === 'dark' 
                              ? 'rgba(255, 255, 255, 0.05)' 
                              : 'rgba(0, 0, 0, 0.03)',
                            color: theme.textPrimary,
                          }}
                          placeholder="例如: 2023-01-01T09:00:00Z"
                        />
                      </div>
                    </div>
                  )}
                  
                  <div className="crawler-modal-footer">
                    <CustomButton 
                      type="default"
                      onClick={() => {
                        setShowCreateModal(false);
                        setEditingConfig(null);
                      }}
                    >
                      取消
                    </CustomButton>
                    <CustomButton 
                      type="primary"
                      onClick={editingConfig ? handleSaveConfig : handleCreateConfig}
                      disabled={!newConfig.name}
                    >
                      {editingConfig ? '保存配置' : '创建配置'}
                    </CustomButton>
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        </motion.div>
      )}

      {/* 日志查看模态框 */}
      {showLogModal.jobId && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="crawler-modal-overlay"
        >
          <motion.div
            initial={{ scale: 0.7, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.7, opacity: 0 }}
            className="crawler-modal-content crawler-log-modal"
            style={{
              backgroundColor: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              boxShadow: theme.cardShadow
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div 
              className="crawler-modal-header"
              style={{ 
                borderBottom: `1px solid ${theme.borderColor}`,
              }}
            >
              <h2 className="crawler-modal-title" style={{ 
                color: theme.textPrimary,
              }}>
                任务日志
              </h2>
              <button
                className="crawler-modal-close"
                style={{
                  color: theme.textSecondary,
                }}
                onMouseEnter={(e) => e.currentTarget.style.color = theme.glowColor}
                onMouseLeave={(e) => e.currentTarget.style.color = theme.textSecondary}
                onClick={() => setShowLogModal({ jobId: null, logs: [] })}
              >
                ×
              </button>
            </div>
            
            <div className="crawler-modal-body">
              <div 
                className="crawler-log-content"
                style={{
                  backgroundColor: mode === 'dark' 
                    ? 'rgba(0, 0, 0, 0.2)' 
                    : 'rgba(0, 0, 0, 0.03)',
                  border: `1px solid ${theme.borderColor}`,
                }}
              >
                {showLogModal.logs.map((log, index) => {
                  let logClass = 'crawler-log-entry';
                  if (log.includes('ERROR') || log.includes('error') || log.includes('失败')) {
                    logClass += ' error';
                  } else if (log.includes('WARNING') || log.includes('warning') || log.includes('警告')) {
                    logClass += ' warning';
                  } else if (log.includes('SUCCESS') || log.includes('success') || log.includes('成功')) {
                    logClass += ' success';
                  } else {
                    logClass += ' info';
                  }
                  
                  return (
                    <div 
                      key={index} 
                      className={logClass}
                      style={{
                        color: theme.textPrimary,
                      }}
                    >
                      {log}
                    </div>
                  );
                })}
              </div>
              
              <div className="crawler-modal-footer">
                <CustomButton 
                  type="default"
                  onClick={() => setShowLogModal({ jobId: null, logs: [] })}
                >
                  关闭
                </CustomButton>
              </div>
            </div>
          </motion.div>
        </motion.div>
      )}
    </motion.div>
  );
};

export default CrawlerManager;